package chen.web;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chen.web.user.Account;
import chen.web.user.InternalAccountProvider;
import chen.web.user.SessionSupport;
import chen.web.util.IpUtil;
import chen.web.util.jdbc.wrapper.QueryInfo;

public class InitMyContextFilter implements Filter{

	private SessionSupport ss ;
	
	public void setSessionSupport(SessionSupport ss){
		this.ss = ss;
	}
	
	public static final String Process_Start_Time_Attribute_Name = "Process_Start_Time";
	public static final String Jdbc_Query_Info_Context_Attribute_Name = "Jdbc_Query_Info";
	
	private void initTimer(MyContext context){
		long startTime = System.nanoTime();
		context.setAttribute(Process_Start_Time_Attribute_Name, startTime);
		//初始化
		QueryInfo info = new QueryInfo();
		context.setAttribute(Jdbc_Query_Info_Context_Attribute_Name, info);
	}
	
	public static final String Captcha_Attribute_Name = "_captcha";
	private static final String Captcha_Parameter_Name = "_captcha";
	
	/**
	 * 设置验证码
	 * @param context
	 * @param request
	 */
	private void setCaptcha(MyContext context, HttpServletRequest request){
		String captcha = request.getParameter(Captcha_Parameter_Name);
		if(captcha != null){
			context.setAttribute(Captcha_Attribute_Name, captcha);	
		}
	}

	/**
	 * 为用户生成一个名为uuid的cookie，他的值是一个随机的uuid字符串
	 * 如果用户已经有此cookie，将不会重新生成．因此可用于用户跟踪．
	 * 如果用户浏览器拒绝cookie, 则会每次生成新的uuid
	 * @param request
	 * @param response
	 * @return 
	 */
	private String generateUuidCookie(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		Cookie uuidCookie = null;
		
		//获取uuid cookie
		if(cookies != null){
			for(Cookie cookie : cookies){
				if("uuid".equals(cookie.getName())){
					uuidCookie = cookie;
					break;
				}
			}	
		}
		
		//如果客户端不存在uuid cookie, 则生成一个
		if(uuidCookie == null){
			uuidCookie = new Cookie("uuid", UUID.randomUUID().toString());
			uuidCookie.setPath("/");
			//cookie生命设置为1000天
			uuidCookie.setMaxAge(1000*24*60*60);
			response.addCookie(uuidCookie);
		}
		
		//将uuid放入当前帐号中
		String uuid = uuidCookie.getValue();
		return uuid;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		MyContext context = MyContextProvider.getMyContext();
		if(context == null){
			context = new MyContext();
			MyContextProvider.setMyContext(context);
		} else {
			context.clear();
		}
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		initTimer(context);
		setCaptcha(context, request);
		//为用户生成一个名为uuid的cookie
		String uuid = generateUuidCookie(request, response);
		context.setUuid(uuid);
		//获取ip地址
		String ip = IpUtil.getIpAddress(request);
		context.setIp(ip);
		
		//跟踪当前用户帐号
		Account account = ss.getAccount(request, response);
		//没有跟踪到,则给予公共访客账号
		if(account == null){
			account = InternalAccountProvider.getPublicGuestAccount();
		}
		context.setAccount(account);
		chain.doFilter(req, res);
		MyContextProvider.remove();
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
